const path = require('path');
const { done } = require("./function");
const { accessPath, anyKeyExit } = require("./utils");
const { fileMap } = require("./fileList"); // 获取 Map

async function handleCommandLineArgs (args, targetDir) {
  if (args.length === 0) return false;

  const cmd = args[0].toLocaleLowerCase();
  if (cmd) {
    if (cmd == '-getname') {
      const item = fileMap.get(args[1]);
      const fileIdx = (item ? item.index : -1) + 1;
      if (fileIdx === 0) {
        console.warn('未找到目标文件');
      } else {
        console.log(`目标应于文件 sn_${fileIdx}`);
      }
      await anyKeyExit(fileIdx === 0 ? 1 : 0);
      return true;
    }
    if (cmd == '-create') {
      const modePath = await autoPath(args[1], targetDir)
      if (modePath) console.log(await done({ path: modePath, newFolderName: args[1] }, ''));
      await anyKeyExit(0);
      return true;
    }
  } else {
    console.error('无效的参数:', args[0]);
    console.log('有效参数列表：-getname');
    await anyKeyExit(2);
    return true;
  }
}

async function autoPath (dir, targetDir) {
  if (dir.indexOf(':') > -1) {
    if (await accessPath(dir)) return dir
    else {
      console.error('未找到目标文件：', dir);
      return false;
    }
  } else {
    const fixPath = path.join(targetDir, dir);
    if (await accessPath(fixPath)) return fixPath
    else {
      console.error('未找到目标文件：', fixPath);
      return false;
    }
  }
}

module.exports = { handleCommandLineArgs }
